


//
//  NSMutableAttributedString+Help.m
//  baaaaby-ios
//
//  Created by IsLand on 15/11/6.
//  Copyright © 2015年 baaaaby. All rights reserved.
//

#import "NSMutableAttributedString+Help.h"

@implementation NSMutableAttributedString (Help)

/**
 *  调整字体的大小和行间距
 *
 *  @param str      字体内容
 *  @param spacing  自己的间距
 *  @param fontSize 字体大小
 *
 *  @return 设置好后的字体
 */
+(NSMutableAttributedString *)stringWithAttributed:(NSString *)str lineSpacing:(CGFloat)spacing FontSize:(CGFloat)fontSize
{
    if (!str)
        return nil;
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:str];
    NSMutableParagraphStyle *paraGraphaStyle = [[NSMutableParagraphStyle alloc]init];
    [paraGraphaStyle setLineSpacing:spacing];
    [paraGraphaStyle setLineBreakMode:NSLineBreakByWordWrapping];
    [paraGraphaStyle setAlignment:NSTextAlignmentJustified];
    NSDictionary *dic = @{NSFontAttributeName: [UIFont systemFontOfSize:fontSize],
                          NSParagraphStyleAttributeName : paraGraphaStyle};
    [attributedString addAttributes:dic range:NSMakeRange(0, [str length])];
    return attributedString;
}
/**
 *  计算字体Size
 *
 *  @param string       字体内容
 *  @param spacing      字体间距
 *  @param fontSize     字体大小
 *  @param contentWidth 要显示的内容宽度
 *
 *  @return 字体size
 */
+ (CGSize)getTextSize:(NSString *)string lineSpacing:(CGFloat)spacing FontSize:(CGFloat)fontSize andContentWidth:(CGFloat)contentWidth
{
    if (string.length == 0) return CGSizeZero;
    NSRange range = NSMakeRange(0, 0);
    NSDictionary *dic = [[self stringWithAttributed:string lineSpacing:spacing FontSize:fontSize] attributesAtIndex:0 effectiveRange:&range];;
    CGSize size = [string boundingRectWithSize:CGSizeMake(contentWidth, MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil].size;
    return size;
}

//获取字符串高度
+ (CGFloat)getTextHeight:(NSString *)string lineSpacing:(CGFloat)spacing FontSize:(CGFloat)fontSize andContentWidth:(CGFloat)contentWidth
{
    if (string.length == 0) return 0;
    NSRange range = NSMakeRange(0, 0);
    NSDictionary *dic = [[self stringWithAttributed:string lineSpacing:spacing FontSize:fontSize] attributesAtIndex:0 effectiveRange:&range];;
    CGSize size = [string boundingRectWithSize:CGSizeMake(contentWidth, MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil].size;
    return size.height;
}

@end
